﻿using System.Linq;
using Fujitsu.JiraAnalysis.DAL;
using Fujitsu.JiraAnalysis.JiraRPC;

namespace Fujitsu.JiraAnalysis.ReplicationService.Synchronize
{
    class FixVersionsUpdate
    {
        FixVersionStorage fixVersionStorage = new FixVersionStorage();

        public string Update(Issue dbIssue, RemoteIssue jiraIssue)
        {
            var result = string.Empty;
            foreach (var version in jiraIssue.fixVersions)
            {
                var fixVersionId = fixVersionStorage.CheckAndAdd(dbIssue.ID, version.id);
                if (fixVersionId != null)
                    result += string.Concat(" ", version.name);
            }
            var dbFixVersions = fixVersionStorage.GetFixVersionsOfIssue(dbIssue.ID);
            if (dbFixVersions.Count > jiraIssue.fixVersions.Length)
            {
                foreach (var dbFixVersion in dbFixVersions)
                {
                    if (!jiraIssue.fixVersions.Any(v => (v as RemoteVersion).name == dbFixVersion.Name))
                    {
                        fixVersionStorage.DeleteFixVersion(dbIssue.ID, dbFixVersion.ID);
                    }
                }
            }
            return result;
        }
    }
}
